import hashlib

from django.conf.global_settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from django.http import HttpResponse
from django.template import loader

from AXF.settings import SERVER_HOST, SERVER_PORT
from App.models import Cart


def hash_str(source):
    # 对传入数据进行哈希sha512加密,并返回16进制
    return hashlib.new('sha512', source.encode('utf-8')).hexdigest()


def sendmail(username, receive, u_token):
    subject = "用户激活"
    message = "<h2>请点击下方链接激活账号</h2>"
    from_email = EMAIL_HOST_USER
    data = {
        'username': username,
        'activate_url': 'http://{}:{}/app/active/?u_token={}'.format(SERVER_HOST, SERVER_PORT, u_token)

    }
    html_message = loader.get_template('user/activate.html').render(data)

    recipient_list = [receive, ]

    send_mail(subject=subject, message=message, from_email=from_email, recipient_list=recipient_list,
              html_message=html_message)


def get_total_price():
    carts = Cart.objects.filter(c_is_select=True)
    total = 0
    for cart in carts:
        total += cart.c_goods_num * cart.c_goods.price
    return '{:.2f}'.format(total)
